<template>
  <div ref="chartRef" class="trend-chart"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch, computed } from 'vue'
import * as echarts from 'echarts/core'
import { LineChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import { useSensorStore } from '@/stores/sensor'

echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  LineChart,
  CanvasRenderer
])

const chartRef = ref<HTMLElement>()
let chart: echarts.ECharts | null = null
const sensorStore = useSensorStore()

// 处理时间戳显示
const formatTime = (timestamp: string) => {
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
}

// 使用计算属性处理图表数据
const chartData = computed(() => {
  const airTemp = sensorStore.historyData.airTemperature
  const soilTemp = sensorStore.historyData.soilTemperature

  return {
    times: airTemp.map(item => formatTime(item.timestamp)),
    airTemperature: airTemp.map(item => item.value),
    soilTemperature: soilTemp.map(item => item.value)
  }
})

// 监听数据变化
watch(() => sensorStore.historyData, updateChart, { deep: true })

function updateChart() {
  if (!chart) return

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      data: ['空气温度', '土壤温度'],
      textStyle: {
        color: '#fff'
      },
      top: 10
    },
    grid: {
      top: 60,
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: chartData.value.times,
      axisLabel: {
        color: '#fff',
        fontSize: 12,
        margin: 12
      },
      axisLine: {
        lineStyle: {
          color: '#fff'
        }
      }
    },
    yAxis: {
      type: 'value',
      name: '温度(°C)',
      nameTextStyle: {
        color: '#fff',
        fontSize: 14,
        padding: [0, 30, 0, 0]
      },
      axisLabel: {
        color: '#fff',
        formatter: '{value} °C',
        fontSize: 12,
        margin: 12
      },
      axisLine: {
        lineStyle: {
          color: '#fff'
        }
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(255,255,255,0.1)'
        }
      }
    },
    series: [
      {
        name: '空气温度',
        type: 'line',
        smooth: true,
        lineStyle: {
          width: 2,
          color: '#00e4ff'
        },
        symbolSize: 6,
        areaStyle: {
          opacity: 0.3,
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(0,228,255,0.3)'
            },
            {
              offset: 1,
              color: 'rgba(0,228,255,0)'
            }
          ])
        },
        data: chartData.value.airTemperature
      },
      {
        name: '土壤温度',
        type: 'line',
        smooth: true,
        lineStyle: {
          width: 2,
          color: '#ffc93c'
        },
        symbolSize: 6,
        areaStyle: {
          opacity: 0.3,
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(255,201,60,0.3)'
            },
            {
              offset: 1,
              color: 'rgba(255,201,60,0)'
            }
          ])
        },
        data: chartData.value.soilTemperature
      }
    ]
  }

  chart.setOption(option)
}

onMounted(() => {
  if (chartRef.value) {
    chart = echarts.init(chartRef.value)
    updateChart()

    // 监听窗口大小变化
    window.addEventListener('resize', () => {
      chart?.resize()
    })
  }
})

onBeforeUnmount(() => {
  if (chart) {
    chart.dispose()
    chart = null
  }
  window.removeEventListener('resize', () => {
    chart?.resize()
  })
})
</script>

<style scoped>
.trend-chart {
  width: 100%;
  height: 100%;
}
</style> 